package cn.jbt.api.admin.config;

import cn.dev33.satoken.stp.StpInterface;
import cn.jbt.api.admin.entity.SysUser;
import cn.jbt.api.admin.repository.SysUserRepository;
import cn.jbt.api.admin.service.ISysMenuService;
import cn.jbt.api.admin.service.ISysRoleService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

@Component
@Slf4j
@AllArgsConstructor
public class StpInterfaceImpl implements StpInterface {

    private final SysUserRepository sysUserRepository;
    private final ISysRoleService iSysRoleService;
    private final ISysMenuService iSysMenuService;

    /**
     * <h2>返回一个账号所拥有的权限码集合 </h2>
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {

        if (null == loginId) {
            return null;
        }

        SysUser sysUser = sysUserRepository.findFirstById(Long.parseLong(loginId.toString()));
        if (sysUser.getRoot().equals(1)) {
            return iSysMenuService.selectAllPermission();
        } else {
            return iSysMenuService.selectAllPermissionByUserId(sysUser.getId());
        }
    }

    /**
     * <h2>返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)</h2>
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {

        if (null == loginId) {
            return null;
        }

        SysUser sysUser = sysUserRepository.findFirstById(Long.parseLong(loginId.toString()));
        if (sysUser.getRoot().equals(1)) {
            return Collections.singletonList("admin");
        } else {
            return iSysRoleService.selectAllPermissionByUserId(sysUser.getId());
        }
    }
}
